package codetop.kuaishou.T1339;

import util.TreeNode;

/**
 * @Author: 18362
 * @Create: 2022-09-16 1:23:34 星期五
 */
class Solution {

    private long maxProd = 0;
    private long totalSum;

    public int maxProduct(TreeNode root) {
        totalSum = tranverse(root);
        dfs(root);
        return (int) (maxProd % 1000000007);
    }

    private int tranverse(TreeNode root) {
        if (root == null)
            return 0;
        int sum = tranverse(root.left) + tranverse(root.right) + root.val;
        root.val = sum;
        return sum;
    }

    private void dfs(TreeNode root) {
        if (root.left != null) {
            maxProd = Math.max(maxProd, (long)(root.left.val) * (long)(totalSum - root.left.val));
            dfs(root.left);
        }
        if (root.right != null) {
            maxProd = Math.max(maxProd, (long)(root.right.val) * (long)(totalSum - root.right.val));
            dfs(root.right);
        }
    }
}